package model

import (
	"context"
	"errors"
	"time"

	"gorm.io/gorm"
)

type CommentIndex struct {
	gorm.Model
	ObjectId   uint
	ObjectType int `gorm:"default:0;column:object_type;check:object_type IN (0,1)"`
	UserId     int
	Root       int
	Parent     int
	LikeCount  int
	Attrs      int `gorm:"column:attrs;check:attrs IN (0,1,2,3)"`
}

// BatchInsertComments 批量插入评论
func (m *defaultCommentModel) BatchInsertComments(
	ctx context.Context,
	indexes []*CommentIndex,
	contents []*CommentContent,
) error {
	if len(indexes) != len(contents) {
		return errors.New("索引和内容数量不匹配")
	}

	return m.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		// 1. 批量插入CommentIndex
		if err := tx.CreateInBatches(indexes, 100).Error; err != nil {
			return err
		}

		// 2. 设置关联ID并插入CommentContent
		for i := range contents {
			contents[i].CommentIndexId = indexes[i].ID
			contents[i].CreatedAt = time.Now()
		}

		return tx.CreateInBatches(contents, 100).Error
	})
}
